#include "url.h"
#include <regex.h>
#include <syslog.h>
#include <string.h>

static int		domain_init_flag = 0;
static regex_t	domain_regex;
/*
 * 初始化URL域名库
 */
void url_init()
{
	const char*		purls		= "[^\\.]+(\\.com|\\.gov|\\.net|\\.int|\\.edu"
		"|\\.mil|\\.org)?\\.[^\\.]+$";
	int				n;
	char			buf[256]	= {0};
	
	n = regcomp(&domain_regex, purls, REG_EXTENDED | REG_ICASE);
	if( 0 != n )
	{
		regerror(n, &domain_regex, buf, sizeof(buf));
		syslog(LOG_ERR, "regcomp error: %s\n", buf);
		return;
	}
	domain_init_flag = 1;
}
/*
 * 分离URL的顶级域名
 */
char* url_get_domain(const char* url, char* domain)
{
	regmatch_t		pmatch[1]		= {0};
	size_t			nmatch			= 1;
	int				n;
	char*			topdomain		= domain;
	int				i;

	// 初始化
	if(0 == domain_init_flag)
	{
		url_init();
	}
	// 执行匹配
	n = regexec(&domain_regex, url, nmatch, pmatch, 0);
	if( 0 != n || -1 == pmatch[0].rm_so )
	{
		pmatch[0].rm_so = 0;
		pmatch[0].rm_eo = strlen(url);
	}
	// 转换为小写, 去除'符号
	for(i = pmatch[0].rm_so; 
			'\0' != url[i] && i < pmatch[0].rm_eo; 
			i++)
	{
		if('\'' == url[i])
		{
			continue;
		}
		*(topdomain++) = tolower(url[i]);
	}
	return domain;
}

